package china.z.console.config.shiro;

import china.z.console.common.util.MD5Util;
import china.z.console.data.entity.AcctRole;
import china.z.console.data.entity.AcctUser;
import china.z.console.module.service.AcctUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

public class ShiroRealm extends AuthorizingRealm {

    @Autowired
    private AcctUserService acctUserService;

    /**
     * 权限信息
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        /*
         * 当没有使用缓存的时候，不断刷新页面的话，这个代码会不断执行，
         * 当其实没有必要每次都重新设置权限信息，所以我们需要放到缓存中进行管理；
         * 当放到缓存中时，这样的话，doGetAuthorizationInfo就只会执行一次了，
         * 缓存过期之后会再次执行。
         */
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        String username = (String) principalCollection.getPrimaryPrincipal();

        //添加角色和权限
        AcctUser acctUser = acctUserService.findByUsername(username);
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        for (AcctRole role : acctUser.getAcctRoles()) {
            //添加角色
            simpleAuthorizationInfo.addRole(role.getCode());
            /*for (AcctPermission permission:role.getAcctPermissions) {
                //添加权限
                simpleAuthorizationInfo.addStringPermission(permission.getCode());
            }*/
        }
        return simpleAuthorizationInfo;
    }

    /**
     * 认证信息
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取用户的输入的账号.
        UsernamePasswordToken usernamePasswordToken=(UsernamePasswordToken)authenticationToken;
        String username = usernamePasswordToken.getUsername();

        AcctUser acctUser = acctUserService.findByUsername(username);
        if (null == acctUser) {
            return null;
        } else {
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(
                    //用户名
                    acctUser.getUsername(),
                    //密码
                    acctUser.getPassword(),
                    getName());
            return simpleAuthenticationInfo;
        }
    }
}
